import { defineStore } from 'pinia';
import { 
  getArticleList, 
  queryArticles, 
  getArticleDetail, 
  addArticle, 
  updateArticle, 
  updateArticleStatus, 
  deleteArticle,
  getArticleCategoryTree,
  addArticleCategory,
  updateArticleCategory,
  toggleArticleCategoryActive,
  deleteArticleCategory,
  checkCategoryNameUnique
} from '@/api/article';
import { ElMessage } from 'element-plus';

export const useArticleStore = defineStore('articleStore', {
  state: () => ({
    articles: [],
    categories: [],
    categoryTree: [],
    currentArticle: null,
    total: 0,
    page: 1,
    pageSize: 10,
    loading: false,
    submitting: false,
    queryParams: {
      title: '',
      status: '',
      categoryId: ''
    }
  }),
  getters: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    hasPrevPage() {
      return this.page > 1;
    },
    hasNextPage() {
      return this.page < this.totalPages;
    },
  },
  actions: {
    // 设置当前页码
    setPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.page = page;
        this.fetchArticles();
      }
    },
    // 设置每页条数
    setPageSize(pageSize) {
      this.pageSize = pageSize;
      this.page = 1;
      this.fetchArticles();
    },
    // 获取文章列表
    async fetchArticles() {
      this.loading = true;
      try {
        const response = await getArticleList({
          pageIndex: this.page,
          pageSize: this.pageSize,
        });
        if (response && response.code === 200 && response.data) {
          this.articles = response.data.items || [];
          this.total = response.data.totalCount || 0;
        } else {
          this.articles = [];
          this.total = 0;
          ElMessage.error('获取文章列表失败: 无效的响应格式');
        }
      } catch (error) {
        ElMessage.error('获取文章列表失败: ' + (error.message || '未知错误'));
        console.error('Failed to fetch articles list:', error);
      } finally {
        this.loading = false;
      }
    },
    // 条件查询文章
    async searchArticles(params) {
      this.loading = true;
      try {
        const response = await queryArticles({
          ...params,
          pageIndex: this.page,
          pageSize: this.pageSize
        });
        if (response && response.code === 200 && response.data) {
          this.articles = response.data.items || [];
          this.total = response.data.totalCount || 0;
          this.queryParams = params;
        } else {
          this.articles = [];
          this.total = 0;
          ElMessage.error('查询文章失败: 无效的响应格式');
        }
      } catch (error) {
        ElMessage.error('查询文章失败: ' + (error.message || '未知错误'));
        console.error('Failed to search articles:', error);
      } finally {
        this.loading = false;
      }
    },
    // 获取文章详情
    async fetchArticleDetail(articleId) {
      this.loading = true;
      try {
        const response = await getArticleDetail(articleId);
        if (response && response.code === 200) {
          this.currentArticle = response.data;
          return response.data;
        } else {
          ElMessage.error('获取文章详情失败: ' + (response?.message || '未知错误'));
          return null;
        }
      } catch (error) {
        ElMessage.error('获取文章详情失败: ' + (error.message || '未知错误'));
        console.error('Failed to fetch article detail:', error);
        return null;
      } finally {
        this.loading = false;
      }
    },
    // 添加文章
    async createArticle(articleData) {
      this.submitting = true;
      try {
        const response = await addArticle(articleData);
        if (response && response.code === 200) {
          ElMessage.success('文章创建成功');
          this.fetchArticles();
          return true;
        } else {
          ElMessage.error('创建文章失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('创建文章失败: ' + (error.message || '未知错误'));
        console.error('Failed to create article:', error);
        return false;
      } finally {
        this.submitting = false;
      }
    },
    // 更新文章
    async modifyArticle(articleData) {
      this.submitting = true;
      try {
        const response = await updateArticle(articleData);
        if (response && response.code === 200) {
          ElMessage.success('文章更新成功');
          this.fetchArticles();
          return true;
        } else {
          ElMessage.error('更新文章失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('更新文章失败: ' + (error.message || '未知错误'));
        console.error('Failed to update article:', error);
        return false;
      } finally {
        this.submitting = false;
      }
    },
    // 更新文章状态
    async changeArticleStatus(articleId, status) {
      this.loading = true;
      try {
        const response = await updateArticleStatus(articleId, status);
        if (response && response.code === 200) {
          ElMessage.success('文章状态更新成功');
          this.fetchArticles();
          return true;
        } else {
          ElMessage.error('更新文章状态失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('更新文章状态失败: ' + (error.message || '未知错误'));
        console.error('Failed to update article status:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    // 删除文章
    async removeArticle(articleId) {
      this.loading = true;
      try {
        const response = await deleteArticle(articleId);
        if (response && response.code === 200) {
          ElMessage.success('文章删除成功');
          this.fetchArticles();
          return true;
        } else {
          ElMessage.error('删除文章失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('删除文章失败: ' + (error.message || '未知错误'));
        console.error('Failed to delete article:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    // 获取分类树
    async fetchCategoryTree() {
      this.loading = true;
      try {
        const response = await getArticleCategoryTree();
        if (response && response.code === 200) {
          this.categoryTree = response.data || [];
          return response.data;
        } else {
          ElMessage.error('获取分类树失败: ' + (response?.message || '未知错误'));
          return [];
        }
      } catch (error) {
        ElMessage.error('获取分类树失败: ' + (error.message || '未知错误'));
        console.error('Failed to fetch category tree:', error);
        return [];
      } finally {
        this.loading = false;
      }
    },
    // 添加分类
    async createCategory(categoryData) {
      this.submitting = true;
      try {
        const response = await addArticleCategory(categoryData);
        if (response && response.code === 200) {
          ElMessage.success('分类创建成功');
          await this.fetchCategoryTree();
          return true;
        } else {
          ElMessage.error('创建分类失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('创建分类失败: ' + (error.message || '未知错误'));
        console.error('Failed to create category:', error);
        return false;
      } finally {
        this.submitting = false;
      }
    },
    // 更新分类
    async modifyCategory(categoryData) {
      this.submitting = true;
      try {
        const response = await updateArticleCategory(categoryData);
        if (response && response.code === 200) {
          ElMessage.success('分类更新成功');
          await this.fetchCategoryTree();
          return true;
        } else {
          ElMessage.error('更新分类失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('更新分类失败: ' + (error.message || '未知错误'));
        console.error('Failed to update category:', error);
        return false;
      } finally {
        this.submitting = false;
      }
    },
    // 切换分类状态
    async toggleCategoryActive(categoryId) {
      this.loading = true;
      try {
        const response = await toggleArticleCategoryActive(categoryId);
        if (response && response.code === 200) {
          ElMessage.success('分类状态切换成功');
          await this.fetchCategoryTree();
          return true;
        } else {
          ElMessage.error('切换分类状态失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('切换分类状态失败: ' + (error.message || '未知错误'));
        console.error('Failed to toggle category active:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    // 删除分类
    async removeCategory(categoryId) {
      this.loading = true;
      try {
        const response = await deleteArticleCategory(categoryId);
        if (response && response.code === 200) {
          ElMessage.success('分类删除成功');
          await this.fetchCategoryTree();
          return true;
        } else {
          ElMessage.error('删除分类失败: ' + (response?.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('删除分类失败: ' + (error.message || '未知错误'));
        console.error('Failed to delete category:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    // 检查分类名称是否唯一
    async checkCategoryNameUnique(params) {
      try {
        const response = await checkCategoryNameUnique(params);
        return response?.data || false;
      } catch (error) {
        console.error('Failed to check category name unique:', error);
        return false;
      }
    },
    // 重置查询条件
    resetSearch() {
      this.queryParams = {
        title: '',
        status: '',
        categoryId: ''
      };
      this.page = 1;
      this.fetchArticles();
    },
    // 初始化数据
    async initData() {
      await Promise.all([
        this.fetchArticles(),
        this.fetchCategoryTree()
      ]);
    }
  }
});